package com.ebring.shareEducation.service.impl;

import com.ebring.shareEducation.bean.*;
import com.ebring.shareEducation.dao.CurrencyMapper;
import com.ebring.shareEducation.dao.TraderecordsMapper;
import com.ebring.shareEducation.dao.TransactionMapper;
import com.ebring.shareEducation.dao.UstAccountMapper;
import com.ebring.shareEducation.service.TransationService;
import com.ebring.shareEducation.utils.DateUtil;
import com.ebring.shareEducation.utils.RspMsg;
import com.ebring.shareEducation.utils.UuidUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TransactionServiceImpl implements TransationService {


    @Autowired
    private TransactionMapper transactionMapper;

    @Autowired
    private CurrencyMapper currencyMapper;

    @Autowired
    private UstAccountMapper ustAccountMapper;

    @Autowired
    private TraderecordsMapper traderecordsMapper;

    @Override
    public RspMsg<Transaction> insertTrade(String userid,String userids,BigDecimal amount, String bankid, String bid,Integer type) {
        RspMsg rspMsg = new RspMsg();
        if(amount==null||amount.compareTo(new BigDecimal(0))<=0){
            rspMsg.setError();
            rspMsg.setMsg("买入数量异常"+amount);
            return rspMsg;
        }
        if(bankid==null||"".equals(bankid)){
            rspMsg.setError();
            rspMsg.setMsg("请选择支付方式");
            return rspMsg;
        }
        if(bid==null||"".equals(bid)){
            rspMsg.setError();
            rspMsg.setMsg("币不存在");
            return rspMsg;
        }

        Currency currency=currencyMapper.selectByPrimaryKey(bid);
        if(currency==null||"".equals(currency)){
            rspMsg.setError();
            rspMsg.setMsg("虚拟币不存在！");
            return rspMsg;
        }

        if(amount.compareTo(currency.getMin())<0){
            rspMsg.setError();
            rspMsg.setMsg("买入数量小于最小买入数量");
            return rspMsg;
        }
       // Exception exception = new Exception(Ustaccount.class);
        Example example = new Example(Ustaccount.class);
        example.or().andEqualTo("userid",userids);
        Ustaccount ustaccount = ustAccountMapper.selectByExample(example).get(0);
        // Ustaccount ustaccount=ustAccountMapper.s(userids);
        BigDecimal balance=ustaccount.getAvailable();
        BigDecimal ye=balance.subtract(amount);
        if(ye==null||ye.compareTo(new BigDecimal(0))<0){
            rspMsg.setError();
            rspMsg.setMsg("余额不足无法购买！");
            return rspMsg;
        }else{
            BigDecimal big=ustaccount.getFreeze();
            BigDecimal feesum=big.add(amount);
            ustaccount.setFreeze(feesum);
            ustaccount.setAvailable(ye);
        }
        Transaction transaction=new Transaction();
        transaction.setId(UuidUtils.getNumberIds(5));
        transaction.setCoinId(bid);
        transaction.setCreateTime(DateUtil.getStringDate());
        transaction.setBankId(bankid);
        transaction.setFee(currency.getFee());
        transaction.setStatus(1);
        transaction.setTotal(amount);
        transaction.setRate(currency.getRate());
        transaction.setType(type);
        transaction.setUserId(userid);
        transaction.setMuserid(userids);
        int i = transactionMapper.insertSelective(transaction);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("新增失败");
        }else{
            int a=ustAccountMapper.updateByPrimaryKey(ustaccount);
            if(a==0){
                rspMsg.setError();
                rspMsg.setMsg("修改失败");
            }else{
                rspMsg.setOK();
                rspMsg.setMsg("新增成功");
            }


        }


        return rspMsg;

    }

    @Override
    public RspMsg<Transaction> updateTrade(Transaction transaction) {
        return null;
    }

    @Override
    public RspMsg<Transaction> selectTradeById(String id) {
        Transaction tra=new Transaction();
        RspMsg rspMsg = new RspMsg();
        List<Transaction> tradeList = transactionMapper.findTradeById(tra.setId(id));
        if (tradeList.isEmpty() || tradeList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关数据");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setResult(tradeList);
        return rspMsg;
    }

    @Override
    public RspMsg<Transaction> DeleteTrade(String[] Id) {
        return null;
    }

    @Override
    @Transactional
    public RspMsg<Transaction> updateTran(String id) {
        RspMsg rspMsg = new RspMsg();
        Transaction transaction =transactionMapper.selectByPrimaryKey(id);
        if(transaction==null||"".equals(transaction)){
            rspMsg.setError();
            rspMsg.setMsg("没有订单记录");
        }else {
            transaction.setStatus(3);
            transaction.setProcessTime(DateUtil.getStringDate());
            transaction.setHandlerId(transaction.getMuserid());
            int a = transactionMapper.updateByPrimaryKeySelective(transaction);
            if (a == 0) {
                rspMsg.setError();
                rspMsg.setMsg("更新信息失败");
            } else {
                Transaction transaction1 = new Transaction();
                transaction1.setId(UuidUtils.getNumberIds(5));
                transaction1.setCoinId(transaction.getCoinId());
                transaction1.setCreateTime(DateUtil.getStringDate());
                transaction1.setBankId(transaction.getBankId());
                transaction1.setFee(transaction.getFee());
                transaction1.setProcessTime(DateUtil.getStringDate());
                transaction1.setStatus(3);
                transaction1.setTotal(transaction.getTotal());
                transaction1.setRate(transaction.getRate());
                transaction1.setType(1);
                transaction1.setUserId(transaction.getUserId());
                transaction1.setMuserid(transaction.getMuserid());
                int i = transactionMapper.insertSelective(transaction1);
                if (i == 0) {
                    rspMsg.setError();
                    rspMsg.setMsg("新增信息失败");
                } else {
                    Traderecords traderecords = new Traderecords();
                    traderecords.setId(UuidUtils.getNumberIds(8));
                    traderecords.setMarkId("001");
                    traderecords.setBuyId(transaction.getUserId());
                    traderecords.setSellId(transaction.getMuserid());
                    traderecords.setPrice(new BigDecimal(1.0));
                    traderecords.setCount(transaction.getTotal());
                    traderecords.setSum(traderecords.getCount().multiply(traderecords.getPrice()));
                    traderecords.setBuyFee(transaction.getFee());
                    traderecords.setSellFee(transaction.getFee());
                    traderecords.setType("买入");
                    traderecords.setTime(DateUtil.getStringDate());
                    int b = traderecordsMapper.insertSelective(traderecords);
                    if (b == 0) {
                        rspMsg.setError();
                        rspMsg.setMsg("新增信息失败");
                    } else {

                        Ustaccount ustaccount=ustAccountMapper.selectPayUseridandbid(transaction.getMuserid(),transaction.getCoinId());
                        Ustaccount ustaccount1=ustAccountMapper.selectPayUseridandbid(transaction.getUserId(),transaction.getCoinId());
                        BigDecimal total=traderecords.getCount();
                        BigDecimal djsl=ustaccount.getFreeze();
                        BigDecimal ye=ustaccount.getBalance();
                        ustaccount.setFreeze(djsl.subtract(total));
                        ustaccount.setBalance(ye.subtract(total));
                        ustaccount1.setBalance(ustaccount1.getBalance().add(total));
                        ustaccount1.setAvailable(ustaccount1.getAvailable().add(total));
                        int c=ustAccountMapper.updateByPrimaryKey(ustaccount);
                        if(c==0){
                            rspMsg.setError();
                            rspMsg.setMsg("修改余额失败");
                        }else {
                            int d=ustAccountMapper.updateByPrimaryKey(ustaccount1);
                            rspMsg.setOK();
                            rspMsg.setMsg("修改余额成功");
                        }
                    }

                }
            }
        }
        return rspMsg;
    }


    @Override
    public RspMsg<Transaction> updateTrans(String id) {
        RspMsg rspMsg = new RspMsg();
        Transaction transaction =transactionMapper.selectByPrimaryKey(id);
        transaction.setStatus(2);
        transaction.setProcessTime(DateUtil.getStringDate());
        transaction.setHandlerId(transaction.getMuserid());
        int a=transactionMapper.updateByPrimaryKeySelective(transaction);
        if(a==0){
            rspMsg.setError();
            rspMsg.setMsg("更新信息失败");
        }else {
            rspMsg.setOK();
            rspMsg.setMsg("更新信息成功");
            }

        return rspMsg;
    }
    @Override
    public RspMsg<Transaction> selectTradefind() {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<Transaction> tradeList = transactionMapper.findTradeAll();
        if (tradeList.isEmpty() || tradeList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关数据");
            return rspMsg;
        }
        PageInfo<Transaction> pageInfo = new PageInfo<>(tradeList);
        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("tradeList", tradeList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }
    @Override
    public RspMsg<List<Transaction>> findTrade(Transaction transaction) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<Transaction> tradeList = transactionMapper.findTradeById(transaction);
        if (tradeList.isEmpty() || tradeList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关订单");
            return rspMsg;
        }

        PageInfo<Transaction> pageInfo = new PageInfo<>(tradeList);

        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("tradeList", tradeList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }
}
